<?php

/**
 * 名称：ContentAction
 * 描述：内容管理
 * 作者：lan 时间：2013-05-02
 * 版本号：V1.0.0
 * ========================历史版本=================================
 * 序号	 版本号 	日期			姓名	 	描述
 * 1 	V1.0.0 	2013-05-02 	lan  	内容管理
 * ========================历史版本=================================
 * 说明：请在有更改程序的时候修改以上注释
 */
class ContentAction extends CommonAction {

    /**
     * 广告管理
     * Create Data <2013-05-02>
     */
    public function ad() {
        $data = M('ad')->order('`display_order` ASC,`ad_id` ASC')->select();
        $this->assign('ad', $data);
        $this->assign('place_array', array(
            L('middle'),
            L('head'),
            L('leftDown'),
            L('rightDown'),
            L('bottom'),
            L('rightUp')
        ));
        $this->display();
    }

    /**
     * 添加广告
     * Create Data <2013-05-02>
     */
    public function addAd() {
        $this->assign('type', 'add');
        $this->display('addAd');
    }

    /**
     * 编辑广告
     * Create Data <2013-05-02>
     */
    public function editAd() {
        $map['ad_id'] = intval($_GET['id']);
        $ad = M('ad')->where($map)->find();

        $ad_content = unserialize($ad['content']);
        if ($ad_content) {
            $ad['content'] = $ad_content;
            $ad['type_id'] = 3;
        }
        if ($ad['display_type'] == 1) {
            $ad['type_id'] = 1;
        }
        if ($ad['display_type'] == 2) {
            $ad['type_id'] = 2;
        }
        if (empty($ad))
            $this->error(L('parameterError'));
        $this->assign('banner', $ad['content']);
        $this->assign($ad);
        $this->assign('ad_id', $map['ad_id']);
        $this->assign('type', 'edit');
        $this->display('editAd');
    }

    /**
     * 添加广告-提交数据
     * Create Data <2013-05-02>
     */
    public function createAd() {
        $count = count($_POST['banner']);
        $_POST['display_type'] == intval($_POST['display_type']);
        if (($_POST['ad_id'] = intval($_POST['ad_id'])) <= 0)
            unset($_POST['ad_id']);

        if ($_POST['display_type'] == 3) {
            import("ORG.Net.UploadFile");
            $upload = new UploadFile(); // 实例化上传类
            $upload->maxSize = 3145728; // 设置附件上传大小
            $upload->allowExts = array(
                'jpg',
                'gif',
                'png',
                'jpeg'
            ); // 设置附件上传类型
            $upload->savePath = './data/uploads/image/'; // 设置附件上传目录
            $upload->saveRule = 'uniqid'; //设置上传文件规则
            if (!$upload->upload()) { // 上传错误提示错误信息
                $this->error($upload->getErrorMsg());
            } else { // 上传成功 获取上传文件信息
                $info = $upload->getUploadFileInfo();
                $this->addAttach('banner', $info);
                $_POST['content'] = __ROOT__ . '/data/uploads/image/' . $info[0]["savename"];
                foreach ($_POST['bannerUrl'] as $v) {
                    if (empty($v)) {
                        $this->error('URL' . L('notNull'));
                    }
                }
                foreach ($info as $k => $v) {
                    $url[$k]['img'] = __ROOT__ . '/data/uploads/image/' . $v['savename'];
                    $url[$k]['url'] = $_POST['bannerUrl'][$k];
                }
                foreach ($_POST['bannerOld'] as $key => $value) {
                    $url[] = array(
                        'img' => $value,
                        'url' => $_POST['bannerUrlOld'][$key]
                    );
                }
                $count = count($url);
                if ($count <= 1) {
                    $this->error(L('bannerCountError'));
                }
                $url = serialize($url);
                $_POST['content'] = $url;
            }
        }

        $_POST['place'] = intval($_POST['place']);
        $_POST['is_active'] = intval($_POST['is_active']) == 0 ? '0' : '1';
        $_POST['is_closable'] = 0;
        $_POST['mtime'] = time();
        if (!isset($_POST['ad_id']))
            $_POST['ctime'] = time();

        // 数据检查
        if (empty($_POST['title']))
            $this->error(L('title') .
                    L('notNull'));
        if ($_POST['place'] < 0 || $_POST['place'] > 5)
            $this->error(L('parameterError'));

        $_LOG['uid'] = $this->mid;
        $_LOG['type'] = isset($_POST['ad_id']) ? '3' : '1';
        $data[] = L("content") . "-" . L("adManage"); // '内容 - 广告管理 '
        isset($_POST['ad_id']) && $data[] = M('ad')->where(array('ad_id' => intval($_POST['ad_id'])))->find();
        if (isset($_POST['ad_id']))
            unset($data['1']['ctime']);
        unset($data['1']['display_order']);
        if ($_POST['__hash__'])
            unset($_POST['__hash__']);
        $data[] = $_POST;
        $_LOG['data'] = serialize($data);
        $_LOG['ctime'] = time();
        M('AdminLog')->add($_LOG);

        // 提交数据
        $res = isset($_POST['ad_id']) ? M('ad')->save($_POST) : M('ad')->add($_POST);

        // 编辑控制
        $aid = $_GET['id'];
        $editdata = M('ad')->where('ad_id=' . $aid)->find();
        $this->assign('editdata', $editdata);

        if ($res) {
            if (!isset($_POST['ad_id'])) {
                // 为排序方便, 新建完毕后, 将display_order设置为ad_id
                M('ad')->where("`ad_id`=$res")->setField('display_order', $res);
                // 点击添加成功后返回到列表页面。
                $this->assign('jumpUrl', URL('admin/Content/ad'));
                // $this->assign('jumpUrl', URL('admin/Content/addAd'));
            } else {
                $this->assign('jumpUrl', URL('admin/Content/ad'));
            }
            F('_action_ad', null); // 删除广告缓存
            $this->success(L('saveSuccess'));
        } else {
            $this->error(L('saveFails'));
        }
    }

    /**
     * 编辑广告-提交数据
     * Create Data <2013-05-02>
     */
    public function updateAd() {
        $map['ad_id'] = $_POST['ad_id'];
        $res = M('ad')->where($map)->find();
        if ($res['display_type'] == 1) {
            $_POST['content'] = $_POST['content'];
        }
        if ($res['display_type'] == 2) {
            $_POST['content'] = $_POST['content'];
        }
        if ($res['display_type'] == 3) {
            if (empty($_FILES['banner']['name'][0])) {
                //如果没有文件上传
                foreach ($_POST['bannerOld'] as $key => $value) {
                    $content[] = array(
                        'img' => $value,
                        'url' => $_POST['bannerUrlOld'][$key]
                    );
                }
                $countOld = count($content);
                if ($countOld <= 1) {
                    $this->error(L('bannerCountError'));
                }
                $content = serialize($content);
                $_POST['content'] = $content;
                if (empty($_POST['title'])) {
                    $this->error(L('title') . L('notNull'));
                }
            } else {
                import("ORG.Net.UploadFile");
                $upload = new UploadFile(); // 实例化上传类
                $upload->maxSize = 3145728; // 设置附件上传大小
                $upload->allowExts = array(
                    'jpg',
                    'gif',
                    'png',
                    'jpeg'
                ); // 设置附件上传类型
                $upload->savePath = './data/uploads/image/'; // 设置附件上传目录
                $upload->saveRule = 'uniqid'; //设置上传文件规则
                if (!$upload->upload()) { // 上传错误提示错误信息
                    $this->error($upload->getErrorMsg());
                } else { // 上传成功 获取上传文件信息
                    $info = $upload->getUploadFileInfo();
                    $this->addAttach('banner', $info);
                    $_POST['content'] = __ROOT__ . '/data/uploads/image/' . $info[0]["savename"];
                    foreach ($_POST['bannerUrl'] as $v) {
                        if (empty($v)) {
                            $this->error('URL' . L('notNull'));
                        }
                    }
                    foreach ($info as $k => $v) {
                        $url[$k]['img'] = __ROOT__ . '/data/uploads/image/' . $v['savename'];
                        $url[$k]['url'] = $_POST['bannerUrl'][$k];
                    }
                    foreach ($_POST['bannerOld'] as $key => $value) {
                        $url[] = array(
                            'img' => $value,
                            'url' => $_POST['bannerUrlOld'][$key]
                        );
                    }
                    $countNew = count($url);
                    if ($countNew <= 1) {
                        $this->error(L('bannerCountError'));
                    }
                    $url = serialize($url);
                    $_POST['content'] = $url;
                }
            }
            $_POST['place'] = intval($_POST['place']);
            $_POST['is_active'] = intval($_POST['is_active']) == 0 ? '0' : '1';
            $_POST['is_closable'] = 0;
            $_POST['mtime'] = time();
            if (!isset($_POST['ad_id']))
                $_POST['ctime'] = time();
        }

        $_LOG['uid'] = $this->mid;
        $_LOG['type'] = isset($_POST['ad_id']) ? '3' : '1';
        $data[] = L("content") . "-" . L("adManage"); // '内容 - 广告管理 '
        isset($_POST['ad_id']) && $data[] = M('ad')->where(array('ad_id' => intval($_POST['ad_id'])))->find();
        if (isset($_POST['ad_id']))
            unset($data['1']['ctime']);
        unset($data['1']['display_order']);
        if ($_POST['__hash__'])
            unset($_POST['__hash__']);
        $data[] = $_POST;
        $_LOG['data'] = serialize($data);
        $_LOG['ctime'] = time();
        M('AdminLog')->add($_LOG);

        // 提交数据
        $res = isset($_POST['ad_id']) ? M('ad')->save($_POST) : M('ad')->add($_POST);

        // 编辑控制
        $aid = $_GET['id'];
        $editdata = M('ad')->where('ad_id=' . $aid)->find();
        $this->assign('editdata', $editdata);

        if ($res !== false) {
            if (!isset($_POST['ad_id'])) {
                // 为排序方便, 新建完毕后, 将display_order设置为ad_id
                M('ad')->where("`ad_id`=$res")->setField('display_order', $res);
                // 点击添加成功后返回到列表页面。
                $this->assign('jumpUrl', URL('admin/Content/ad'));
                // $this->assign('jumpUrl', URL('admin/Content/addAd'));
            } else {
                $this->assign('jumpUrl', URL('admin/Content/ad'));
            }
            F('_action_ad', null); // 删除广告缓存
            $this->success(L('saveSuccess'));
        } else {
            $this->error(L('saveFails'));
        }
    }

    /**
     * 删除广告
     * Create Data <2013-05-02>
     */
    public function deleteAd() {
        if (empty($_POST['ids'])) {
            echo 0;
            exit();
        }
        $map['ad_id'] = array(
            'in',
            $_POST['ids']
        );

        $_LOG['uid'] = $this->mid;
        $_LOG['type'] = '2';
        $data[] = L("content") . "-" . L("adManage"); // '内容 - 广告管理 '
        $data[] = M('ad')->where($map)->select();
        $_LOG['data'] = serialize($data);
        $_LOG['ctime'] = time();
        M('AdminLog')->add($_LOG);

        echo M('ad')->where($map)->delete() ? '1' : '0';
        F('_action_ad', null); // 删除广告缓存
    }

    /**
     * 删除轮播
     * Create Data <2013-05-02>
     */
    public function deleteBanner() {
        echo "1";
    }

    /**
     * 排序广告记录
     * Create Data <2013-05-02>
     */
    public function moveAd() {
        $_POST['ad_id'] = intval($_POST['ad_id']);
        $_POST['baseid'] = intval($_POST['baseid']);
        if ($_POST['ad_id'] <= 0 || $_POST['baseid'] <= 0) {
            echo 0;
            exit();
        }

        // 获取详情
        $map['ad_id'] = array(
            'in',
            array(
                $_POST['ad_id'],
                $_POST['baseid']
            )
        );
        $res = M('ad')->where($map)->field('ad_id,display_order')->select();
        if (count($res) < 2) {
            echo 0;
            exit();
        }

        // 转为结果集为array('id'=>'order')的格式
        foreach ($res as $v) {
            $order[$v['ad_id']] = intval($v['display_order']);
        }
        unset($res);

        // 交换order值
        $res = M('ad')->where('`ad_id`=' . $_POST['ad_id'])->setField('display_order', $order[$_POST['baseid']]);
        $res = $res && M('ad')->where('`ad_id`=' . $_POST['baseid'])->setField('display_order', $order[$_POST['ad_id']]);
        F('_action_ad', null); // 删除广告缓存
        if ($res)
            echo 1;
        else
            echo 0;
    }

    /**
     * 保存上传文件信息到附件表
     *
     * @param string $attach_type   附件类型
     * @param array  $upload_info 	上传文件信息
     * Create Data <2013-05-02>
     */
    public function addAttach($attach_type = 'attach', $upload_info) {
        $attach = M('Attach'); //实例化Attach模型
        foreach ($upload_info as $u) {
            $map['attach_type'] = $attach_type;
            $map['userId'] = 1;
            $map['name'] = $u['name'];
            $map['type'] = $u['type'];
            $map['size'] = $u['size'];
            $map['extension'] = strtolower($u['extension']);
            $map['hash'] = $u['hash'];
            $map['savepath'] = $u['savepath'];
            $map['savename'] = $u['savename'];
            $map['uploadTime'] = time();
            $aid = $attach->add($map);
            $map['id'] = intval($aid);
            $map['key'] = $u['key'];
            unset($map);
        }
    }

    /**
     * 附件管理
     * Create Data <2013-05-02>
     */
    function attach($map) {
        // 查询条件
        $_GET['id'] && $map['id'] = array(
            'in',
            explode(',', $_GET['id'])
        );
        $_GET['userId'] && $map['userId'] = array(
            'in',
            explode(',', $_GET['userId'])
        );
        $_GET['extension'] && $map['extension'] = array(
            'eq',
            $_GET['extension']
        );

        $attach = M('Attach'); //实例化Attach模型
        $list = $this->_list($attach, $map, 10); // 获取附件列表数据分页显示
        // 附件扩展名
        $sql = "SELECT `extension` FROM " . C('DB_PREFIX') . "attach GROUP BY `extension`";
        $res = $attach->query($sql);
        $extension = common('Array')->getSubByKey($res, 'extension');
        $this->assign("rootPath", __ROOT__ . '/data/uploads/');
        $this->assign('extensions', $extension); // 赋值扩展名
        $this->display('attach'); // 输出模板
    }

    /**
     * 搜索附件
     * Create Data <2013-05-02>
     */
    public function searchAttach() {
        $map = $this->_search(array(
            'in' => array(
                'id',
                'userId',
                'extension'
            )
        ));

        $this->attach($map);
    }

    /**
     * 删除附件记录
     * Create Data <2013-05-02>
     */
    public function deleteAttachRecord() {
        $attach = M('Attach');
        if (empty($_POST['ids'])) {
            echo 0;
            exit;
        }
        $map['id'] = array(
            'in',
            $_POST['ids']
        );
        $_LOG['uid'] = $this->mid;
        $_LOG['type'] = '2';
        $data[] = L("content") . "-" . L("attachManage"); // '内容 - 附件管理 ';
        $data[] = $attach->where($map)->select();
        $data[] = array('isFile' => intval($_POST['withfile']));
        $_LOG['data'] = serialize($data);
        $_LOG['ctime'] = time();
        M('AdminLog')->add($_LOG);

        echo $attach->where($map)->delete() ? '1' : '0';
    }

    /**
     * 删除附件记录和文件
     * Create Data <2013-05-02>
     */
    public function deleteAttachFile() {
        $attach = M('Attach');
        if (empty($_POST['ids'])) {
            echo 0;
            exit;
        }
        $map['id'] = array(
            'in',
            $_POST['ids']
        );
        $_LOG['uid'] = $this->mid;
        $_LOG['type'] = '2';
        $data[] = L("content") . "-" . L("attachManage"); // '内容 - 附件管理 ';
        $data[] = array('isFile' => intval($_POST['withfile']));
        $data[] = $attach->where($map)->select();
        $_LOG['data'] = serialize($data);
        $_LOG['ctime'] = time();
        M('AdminLog')->add($_LOG);

        $attaches = array();
        $attaches = $attach->where($map)->select();

        // 删除表记录
        echo $attach->where($map)->delete() ? '1' : '0';
        // 删除文件
        foreach ($attaches as $v) {
            $path = $v['savepath'] . $v['savename'];
            if (is_file($path))
                unlink($path);
        }
    }

    public function topic() {
        import("ORG.Util.Page"); // 导入分页类
        if ($_GET['recycle'] == 1) {
            $this->assign('recycle_tab', 'cur'); // 话题回收站
            $map['status'] = 1;
            $this->assign('recycle', $_GET['recycle']);
        } else if ($_GET['recommend'] == 1) {
            $this->assign('recommend_tab', 'cur'); // 推荐话题
            $map['status'] = 0;
            $map['recommend'] = 1;
            $this->assign('recommend', $_GET['recommend']);
        } else {
            $this->assign('topic_tab', 'cur'); // 话题
            $map['status'] = 0;
        }
        if ($_GET['topic_id'] != null && $_GET['topic_id'] != "") {
            $map['topic_id'] = array("in", explode(',', $_GET['topic_id']));
            $this->assign("topic_id", $_GET['topic_id']);
            $this->assign("search", "yes");
        }
        if ($_GET['topic_name'] != null && $_GET['topic_name'] != "") {
            $map['name'] = array("like", "%" . $_GET['topic_name'] . "%");
            $this->assign("topic_name", $_GET['topic_name']);
            $this->assign("search", "yes");
        }
        $count = model('Topic')->where($map)->count();
        $page = new Page($count, 20);
        $data = model('Topic')->where($map)->order('topic_id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
        $show = $page->show(); // 分页显示输出
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 添加/编辑 话题
     */
    public function addtopic() {
        $topicid = $_GET['topic_id'];
        if (!empty($topicid)) {
            $topic = M('weibo_topic')->where('topic_id =' . $topicid)->find();
            $this->assign($topic);
        }
        $this->display();
    }

    /**
     * 添加/编辑 话题
     */
    public function doaddtopic() {
        if (empty($_POST['name'])) {
            $this->error("话题名称不能为空");
        }
        $hastopic = M('weibo_topic')->where("`name` = '" . $_POST['name'] . "'")->getField('topic_id');
        if (!empty($hastopic) && intval($_POST['topic_id']) !== intval($hastopic)) {
            $this->error("该话题已存在");
        }

        $data = $_POST;
        if (empty($_POST['topic_id'])) {
            $data['ctime'] = time();
            $data['recommend'] === "1" && $data['recommend_time'] = time();
            $res = M('weibo_topic')->add($data);
        } else {
            $data['recommend'] === "1" && $data['recommend_time'] = time();
            $res = M('weibo_topic')->save($data);
        }
        if ($res === false) {
            $this->error("操作失败");
        }
        $this->success("操作成功", URL('admin/Content/topic'));
    }

    public function delTopic() {
        if ($_POST['ids'] == null || $_POST['ids'] == "") {
            echo 0;
            exit();
        }

        $ids = $_POST['ids'];
        if ($_POST['isdel'] == "2") {
            $res = model('Topic')->where("`topic_id` in (" . $ids . ")")->delete();
        } else {
            $res = model('Topic')->where("`topic_id` in (" . $ids . ")")->setField("status", $_POST['isdel']);
        }
        echo $res ? 1 : 0;
    }

    public function weibo() {
        import("ORG.Util.Page"); // 导入分页类
        if ($_GET['recycle'] == 1) {
            $this->assign('recycle_tab', 'cur'); // 微博评论回收站
            $map['isdel'] = 1;
            $this->assign('recycle', $_GET['recycle']);
        } else {
            $this->assign('weibo_tab', 'cur'); // 微博
            $map['isdel'] = 0;
        }
        if ($_GET['weibo_id'] != null && $_GET['weibo_id'] != "") {
            $map['w.weibo_id'] = array("in", explode(',', $_GET['weibo_id']));
            $this->assign("weibo_id", $_GET['weibo_id']);
            $this->assign("search", "yes");
        }
        if ($_GET['uid'] != null && $_GET['uid'] != "") {
            $map['w.uid'] = array("in", explode(',', $_GET['uid']));
            $this->assign("uid", $_GET['uid']);
            $this->assign("search", "yes");
        }
        if ($_GET['content'] != null && $_GET['content'] != "") {
            $map['content'] = array("like", "%" . $_GET['content'] . "%");
            $this->assign("content", $_GET['content']);
            $this->assign("search", "yes");
        }
        if ($_GET['is_recommend'] != null && $_GET['is_recommend'] != "") {
        	$map['is_recommend'] = $_GET['is_recommend'];
        	$this->assign("is_recommend", $_GET['is_recommend']);
        	$this->assign("search", "yes");
        }
        if ($_GET['type'] != null && $_GET['type'] != "") {
        	$map['type'] = $_GET['type'];
        	$this->assign("type", $_GET['type']);
        	$this->assign("search", "yes");
        }
        $count = M('Weibo')->where($map)->count();
        $page = new Page($count, 20);
        $data = M('Weibo')->join("as w left join " . C('DB_PREFIX') . "user as u on w.uid = u.uid")->where($map)->field("w.*,u.uname")->order('weibo_id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
        $show = $page->show(); // 分页显示输出
        $this->assign('page', $show); // 赋值分页输出
        //图片的主路径是写死的，为 /data/uploads/
        array_walk($data, function(&$v, $k) {

            $v['type_data'] = unserialize($v['type_data']);
//            dump($v['type_data']);
            //判断它是一维数组还是二维数组，是一维的话转化成二维数组
            foreach ($v['type_data'] as $key => $val) {
                //图片微博才做处理
                if ($v['type'] == 1) {
                    if (!is_array($val)) {
                        $v['type_data'] = array($v['type_data']);
                        break;
                    }
                }
                //如果是存在又拍云的图片，则解析又拍云图片的url地址
                if (!isset($val['thumbmiddleurl'])) {
                    $v['type_data'][$key]['picurl'] = $this->parseYunPicUrl($val['picurl']);
                }
            }
//            dump($v['type_data']);
        });
//        exit;
        $this->assign('data', $data);
        $this->display();
    }

    /**
     * 将又拍云图片的url中的{upyun}替换成真正的url地址
     * @param string $url 需要被替换的url
     * @return string 替换后的真实的url地址
     */
    private function parseYunPicUrl($url) {
        //获取又拍云上图片的前缀
        $yunConfig = include SITE_PATH . '/apps/admin/Conf/yun.php';
        return str_replace('{upyun}', $yunConfig['picdomain'], $url);
    }
    
    public function doRecommendWeibo(){
    	if ($_POST['ids'] == null || $_POST['ids'] == "") {
    		echo 0;
    		exit();
    	}
    	
    	$ids = $_POST['ids'];
		$data = array('is_recommend' => 1,'rectime' => time());
    	$res = M("weibo")->where("`weibo_id` in (" . $ids . ")")->setField($data);
    	echo $res !== false ? 1 : 0;
    }
    
    public function cancelRecommendWeibo(){
    	if ($_POST['ids'] == null || $_POST['ids'] == "") {
    		echo 0;
    		exit();
    	}
    	 
    	$ids = $_POST['ids'];
    	$res = M("weibo")->where("`weibo_id` in (" . $ids . ")")->setField('is_recommend',0);
    	echo $res !== false ? 1 : 0;
    }

    public function delWeibo() {
        if ($_POST['ids'] == null || $_POST['ids'] == "") {
            echo 0;
            exit();
        }

        $ids = $_POST['ids'];
        if ($_POST['isdel'] == "2") {
            $res = M("Weibo")->where("`weibo_id` in (" . $ids . ")")->delete();
        } else {
            $res = M("Weibo")->where("`weibo_id` in (" . $ids . ")")->setField("isdel", $_POST['isdel']);
        }
        echo $res ? 1 : 0;
    }

    private function _formatWeibo() {
        
    }

    /**
     * 评论管理
     * Create Data <2013-05-02>
     */
    public function comment() {
        import("ORG.Util.Page"); // 导入分页类
        //获取URL参数
        $_GET['from_app'] = ($_GET['from_app'] == 'other') ? 'other' : 'weibo';

        if ($_GET['from_app'] == 'weibo') {
            if ($_GET['recycle'] == 1) {
                $this->assign('recycle_tab', 'cur'); // 微博评论回收站
                $map['isdel'] = 1;
                $this->assign('recycle', $_GET['recycle']);
            } else {
                $this->assign('weibo_tab', 'cur'); // 微博
                $map['isdel'] = 0;
            }
            $count = M('weibo_comment')->where($map)->count(); // 查询满足要求的总记录数
            $Page = new Page($count, 20); // 实例化分页类 传入总记录数和每页显示的记录数
            // 进行分页数据查询
            $data = M('weibo_comment')->where($map)->order('comment_id DESC')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        } else {
            $this->assign('other_tab', 'cur'); // 其它应用
            $count = M('comment')->count(); // 查询总记录数
            $Page = new Page($count, 5); // 实例化分页类 传入总记录数和每页显示的记录数
            // 进行分页数据查询
            $data = M('comment')->order('id DESC')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        }
        $show = $Page->show(); // 分页显示输出
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('data', $this->_formatComment($_GET['from_app'], $data));

        $this->display(); // 输出模板
    }

    /**
     * 评论管理
     * Create Data <2013-05-02>
     */
    private function _formatComment($from_app, $data) {
        foreach ($data as $k => $v) {
            if ($from_app == 'weibo') {
                unset($data[$k]);
                $data[$k] = array(
                    'comment_id' => $v['comment_id'],
                    'type' => 'weibo',
                    'content' => $v['content'],
                    'uid' => $v['uid'],
                    'to_uid' => $v['reply_uid'],
                    'url' => URL('home/Space/detail', array('id' => $v['weibo_id'])),
                    'ctime' => $v['ctime'],
                    'comment_ip' => $v['comment_ip'],
                );
            } else if ($from_app == 'other') {
                unset($data[$k]);
                $v = unserialize($v);
                $data[$k] = array(
                    'comment_id' => $v['id'],
                    'type' => $v['type'],
                    'content' => $v['comment'],
                    'uid' => $v['uid'],
                    'to_uid' => $v['to_uid'],
                    'url' => $v['url'],
                    'ctime' => $v['cTime'],
                    'comment_ip' => $v['comment_ip'],
                );
            }
        }
        return $data;
    }

    /**
     * 删除评论
     * Create Data <2013-05-02>
     */
    public function deleteComment() {
        $_POST['from_app'] = $_POST['from_app'] == 'other' ? 'other' : 'weibo';
        $_POST['ids'] = explode(',', $_POST['ids']);
        if (empty($_POST['ids']))
            return;

        if ($_POST['from_app'] == 'weibo') {
            $wcomment = M('WeiboComment');
            $map['comment_id'] = array(
                'in',
                $_POST['ids']
            );
            $_LOG['uid'] = $this->mid;
            $_LOG['type'] = '2';
            $data[] = L("content") . "-" . L("commentManage") . "-" . L("weibo"); // '内容 - 评论管理  - 微博'
            $data[] = $wcomment->where($map)->select();
            $_LOG['data'] = serialize($data);
            $_LOG['ctime'] = time();
            M('AdminLog')->add($_LOG);
            $weiboids = $wcomment->where($map)->field('weibo_id')->select();
            $result = $wcomment->where($map)->delete();
            if ($result) {
                $wids = array();
                foreach ($weiboids as $v) {
                    $wids[] = $v['weibo_id'];
                }
                M('Weibo')->where('weibo_id in (' . implode(',', $wids) . ')')->setDec('comment');
            }
            echo $result ? '1' : '0';
        } else
        if ($_POST['from_app'] == 'other') {
            $comment = M('Comment');
            $map['id'] = array(
                'in',
                $_POST['ids']
            );
            $_LOG['uid'] = $this->mid;
            $_LOG['type'] = '2';
            $data[] = L("content") . "-" . L("commentManage") . "-" . L("otherApp"); // '内容 - 评论管理  - 其它应用'
            $data[] = $comment->where($map)->select();
            $_LOG['data'] = serialize($data);
            $_LOG['ctime'] = time();
            M('AdminLog')->add($_LOG);
            echo $comment->where($map)->delete() ? '1' : '0';
        } else {
            echo 0;
        }
    }

    /**
     * 私信管理
     * Create Data <2013-05-02>
     */
    public function message($map) {
        // 查询条件
        $_GET['message_id'] && $map['message_id'] = array(
            'in',
            explode(',', $_GET['message_id'])
        );
        $_GET['from_uid'] && $map['from_uid'] = array(
            'in',
            explode(',', $_GET['from_uid'])
        );
        $_GET['content'] && $map['content'] = array(
            'like',
            '%' . $_GET['content'] . '%'
        );

        $model = M('MessageContent'); //实例化MessageContent模型
        $list = $this->_list($model, $map, 5); // 获取列表数据分页显示

        $this->display('message'); // 输出模板
    }

    /**
     * 搜索短消息
     * Create Data <2013-05-02>
     */
    public function searchMessage() {
        // 内容模糊查询
        if (isset($_POST['content']) && $_POST['content'] != '') {
            $_POST['content'] = '%' . $_POST['content'] . '%';
        }
        $map = $this->_search(array(
            'in' => array(
                'message_id',
                'from_uid'
            ),
            'like' => array(
                'content'
            )
        ));
        $this->message($map);
    }

    /**
     * 删除短消息
     * Create Data <2013-05-02>
     */
    public function deleteMessage() {
        $Message = M('MessageContent');
        if (empty($_POST['ids'])) {
            echo 0;
            exit;
        }

        $_LOG['uid'] = $this->mid;
        $_LOG['type'] = '2';
        $data[] = L('content') . ' - ' . L('messageManage');
        $map['message_id'] = array(
            'in',
            $_POST['ids']
        );
        $data[] = $Message->where($map)->order('message_id')->select();
        $_LOG['data'] = serialize($data);
        $_LOG['ctime'] = time();
        M('AdminLog')->add($_LOG);

        echo $Message->where($map)->delete() ? '1' : '0';
    }

    /**
     * 通知管理
     * Create Data <2013-05-02>
     */
    public function notify($map) {
        // 查询条件
        $_GET['notify_id'] && $map['notify_id'] = array(
            'in',
            explode(',', $_GET['notify_id'])
        );
        $_GET['from'] && $map['from'] = array(
            'in',
            explode(',', $_GET['from'])
        );
        $_GET['receive'] && $map['receive'] = array(
            'in',
            explode(',', $_GET['receive'])
        );
        $_GET['type'] && $map['type'] = array(
            'eq',
            $_GET['type']
        );

        $model = M('Notify'); //实例化Notify模型
        $list = $this->_list($model, $map, 5); // 获取列表数据分页显示
        // 获取类型
        $sql = "SELECT `type` FROM " . C('DB_PREFIX') . "notify GROUP BY `type`";
        $res = M('')->query($sql);
        $types = common('Array')->getSubByKey($res, 'type');
        $this->assign('types', $types); // 赋值类型输出
        $this->display('notify'); // 输出模板
    }

    /**
     * 搜索通知
     * Create Data <2013-05-02>
     */
    public function searchNotify() {
        $map = $this->_search(array(
            'in' => array(
                'notify_id',
                'from',
                'receive',
                'type'
            )
        ));
        $this->notify($map);
    }

    /**
     * 删除通知
     * Create Data <2013-05-02>
     */
    public function deleteNotify() {
        if (empty($_POST['ids'])) {
            echo 0;
            exit;
        }

        $_LOG['uid'] = $this->mid;
        $_LOG['type'] = '2';
        $data[] = L('content') . ' - ' . L('notifyManage');
        $map['notify_id'] = array(
            'in',
            $_POST['ids']
        );
        $data[] = M('Notify')->where($map)->select();
        $_LOG['data'] = serialize($data);
        $_LOG['ctime'] = time();
        M('AdminLog')->add($_LOG);

        echo M('Notify')->where($map)->delete() ? '1' : '0';
    }

    /**
     * 动态管理
     * Create Data <2013-05-02>
     */
    public function feed($map) {
        // 查询条件
        $_GET['feed_id'] && $map['feed_id'] = array(
            'in',
            explode(',', $_GET['feed_id'])
        );
        $_GET['uid'] && $map['uid'] = array(
            'in',
            explode(',', $_GET['uid'])
        );
        $_GET['type'] && $map['type'] = array(
            'eq',
            $_GET['type']
        );

        $model = M('Feed'); //实例化Feed模型
        $list = $this->_list($model, $map, 5); // 获取列表数据分页显示
        // 获取类型
        $sql = "SELECT `type` FROM " . C('DB_PREFIX') . "feed GROUP BY `type`";
        $res = M('')->query($sql);
        $types = common('Array')->getSubByKey($res, 'type');
        $this->assign('types', $types); // 赋值类型输出

        $this->display('feed'); // 输出模板
    }

    /**
     * 搜索动态
     * Create Data <2013-05-02>
     */
    public function searchFeed() {
        $map = $this->_search(array(
            'in' => array(
                'feed_id',
                'uid',
                'type'
            )
        ));

        $this->feed($map);
    }

    /**
     * 删除动态记录
     * Create Data <2013-05-02>
     */
    public function deleteFeed() {
        $Feed = M('Feed');
        if (empty($_POST['ids'])) {
            echo 0;
            exit;
        }
        $map['feed_id'] = array(
            'in',
            $_POST['ids']
        );
        $_LOG['uid'] = $this->mid;
        $_LOG['type'] = '2';
        $data[] = L('content') . ' - ' . L('feedManage');
        $data[] = $Feed->where($map)->select();
        $_LOG['data'] = serialize($data);
        $_LOG['ctime'] = time();
        M('AdminLog')->add($_LOG);

        echo $Feed->where($map)->delete() ? '1' : '0';
    }

    /**
     * 举报管理
     * Create Data <2013-05-02>
     */
    public function denounce($map) {
        // 查询条件
        $_GET['id'] && $map['id'] = array(
            'in',
            explode(',', $_GET['id'])
        );
        $_GET['uid'] && $map['uid'] = array(
            'in',
            explode(',', $_GET['uid'])
        );
        $_GET['fuid'] && $map['fuid'] = array(
            'in',
            explode(',', $_GET['fuid'])
        );
        $_GET['from'] && $map['from'] = $_GET['from'];
        $map['state'] = $_GET['state'] ? $_GET['state'] : '0';
        // 类型
        $this->assign('state', $map['state']); // 赋值类型输出
        if ($map['state'] == 0) {
            $this->assign('tab0', 'cur');
        } elseif ($map['state'] == 1) {
            $this->assign('tab1', 'cur');
        } elseif ($map['state'] == 2) {
            $this->assign('tab2', 'cur');
        }

        $model = M('Denounce'); //实例化Denounce模型
        $list = $this->_list($model, $map, 5, 'id'); // 获取列表数据分页显示
        if (is_array($map) && sizeof($map) == '1')
            unset($map);

        $this->display('denounce'); // 输出模板
    }

    /**
     * 进入回收站
     * Create Data <2013-05-02>
     */
    public function deleteDenounce() {
        $Denounce = M('Denounce');
        if (empty($_POST['ids'])) {
            echo 0;
            exit;
        }
        $map['id'] = array(
            'in',
            $_POST['ids']
        );

        $_LOG['uid'] = $this->mid;
        $_LOG['type'] = '1';
        $data[] = L("content") . "-" . L("denounceManage") . "-" . L("goRecycle"); // '内容 - 举报管理 - 进入回收站'
        $data[] = $Denounce->where($map)->select();
        $_LOG['data'] = serialize($data);
        $_LOG['ctime'] = time();
        M('AdminLog')->add($_LOG);

        $weiboIds = $Denounce->where($map)->field('aid')->select();
        $weibo_map['weibo_id'] = array(
            'in',
            $weiboIds
        );
        $weibo_set = M('Weibo')->where($weibo_map)->save(array(
            'isdel' => 0
        ));
        $weibo_set = true;
        echo $weibo_set && $Denounce->where($map)->save(array(
            'state' => '1'
        )) ? '1' : '0';
    }

    /**
     * 通过审核
     * Create Data <2013-05-02>
     */
    public function reviewDenounce() {
        if (empty($_POST['ids'])) {
            echo 0;
            exit;
        }
        if ($_POST['from'] == 'group') {
            $map['weibo_id'] = intval($_POST['aid']);
            $data['isdel'] = 0;
            echo M('group_weibo')->where($map)->save($data) ? '1' : '0';
        } else {
            $Denounce = M('Denounce');
            $map['id'] = array(
                'in',
                $_POST['ids']
            );
            $_LOG['uid'] = $this->mid;
            $_LOG['type'] = '1';
            $data[] = L("content") . "-" . L("denounceManage") . "-" . L("throughReview"); //'内容 - 举报管理 - 通过审核';
            $data[] = $Denounce->where($map)->select();
            $_LOG['data'] = serialize($data);
            $_LOG['ctime'] = time();
            M('AdminLog')->add($_LOG);
            $weiboIds = $Denounce->where($map)->field('aid')->select();
            $weibo_map['weibo_id'] = array(
                'in',
                $weiboIds
            );
            $weibo_set = M('Weibo')->where($weibo_map)->save(array(
                'isdel' => 0
            ));
            $weibo_set = true;
            echo $weibo_set && $Denounce->where($map)->save(array(
                'state' => '2'
            )) ? '1' : '0';
        }
    }

    /**
     * 管理日志
     * Create Data <2013-05-02>
     */
    public function adminlog($map) {
        // 查询条件
        $_GET['id'] && $map['id'] = array(
            'in',
            explode(',', $_GET['id'])
        );
        $_GET['uid'] && $map['uid'] = array(
            'in',
            explode(',', $_GET['uid'])
        );
        $_GET['type'] && $map['type'] = array(
            'eq',
            $_GET['type']
        );

        $model = M('AdminLog'); //实例化AdminLog模型
        $list = $this->_list($model, $map, 5, 'id'); // 获取列表数据分页显示

        $this->display('adminlog'); // 输出模板
    }

    /**
     * 查看详细日志
     * Create Data <2013-05-02>
     */
    public function showAdminLog() {
        $map['id'] = $_GET['id'];
        $data = M('AdminLog')->where($map)->find();

        $this->assign($data);
        $this->display();
    }

    /**
     * 搜索日志
     * Create Data <2013-05-02>
     */
    public function searchAdminLog() {
        if (!$_POST['type'])
            unset($_POST['type']);

        $map = $this->_search(array(
            'in' => array(
                'id',
                'uid',
                'type'
            )
        ));
        $this->assign('type', $_POST['type']);
        $this->adminlog($map);
    }

    /**
     * 删除日志
     * Create Data <2013-05-02>
     */
    public function deleteAdminLog() {
        if (empty($_POST['ids'])) {
            echo 0;
            exit;
        }
        $where['id'] = array(
            'in',
            $_POST['ids']
        );
        echo M('AdminLog')->where($where)->delete() ? '1' : '0';
    }

    /**
     * 组装查询条件
     * Create Data <2013-05-02>
     */
    protected function _search($fields) {
        $map = array();
        foreach ($fields as $k => $v) {
            foreach ($v as $field) {
                if (isset($_POST[$field]) && $_POST[$field] != '') {
                    if ($k == 'in')
                        $map[$field] = array(
                            $k,
                            explode(',', $_POST[$field])
                        );
                    else
                        $map[$field] = array(
                            $k,
                            $_POST[$field]
                        );
                }
            }
        }
        return $map;
    }

    public function tag() {
        $taglist = M('tag')->where("tag_alias != ''")->order('tag_id')->select();
        $this->assign('taglist', $taglist);
        $this->display();
    }

    public function createTag() {
        if ($_POST) {
            if (isset($_POST['tag_id']) && !empty($_POST['tag_id'])) {
                $tag_id = intval($_POST['tag_id']);
                $data['tag_id'] = array('neq', $tag_id);
                $data['tag_name'] = $_POST['tag_name'];
                $f = M('tag')->where($data)->find();
                if ($f) {
                    $this->error('标签名称已存在');
                }
                unset($data['uid']);
                $data['tag_alias'] = $_POST['tag_alias'];

                $_LOG['uid'] = $this->mid;
                $_LOG['type'] = '3';
                $datas[] = '内容-标签管理'; // '内容 - 广告管理 '
                $datas[] = M('tag')->where('tag_id=' . $tag_id)->select();
                $_LOG['data'] = serialize($datas);
                $_LOG['ctime'] = time();
                M('AdminLog')->add($_LOG);

                $saveTag = M('tag')->where('tag_id=' . $tag_id)->save($data);
                if (false !== $saveTag) {
                    $this->assign('jumpUrl', URL('admin/Content/tag'));
                    $this->success('编辑成功');
                } else {
                    $this->error('编辑失败');
                }
            } else {
                $data['tag_name'] = $_POST['tag_name'];
                $f = M('tag')->where($data)->find();
                if ($f) {
                    $this->error('标签名称已存在');
                }
                $data['tag_alias'] = $_POST['tag_alias'];
                if (M('tag')->add($data)) {
                    $_LOG['uid'] = $this->mid;
                    $_LOG['type'] = '1';
                    $datas[] = '内容-标签管理'; // '内容 - 广告管理 '
                    $datas[] = $_POST;
                    $_LOG['data'] = serialize($datas);
                    $_LOG['ctime'] = time();
                    M('AdminLog')->add($_LOG);
                    $this->assign('jumpUrl', URL('admin/Content/tag'));
                    $this->success('添加成功');
                } else {
                    $this->error('添加失败');
                }
            }
        }
    }

    public function editTag() {
        if (isset($_GET['id']) && !empty($_GET['id'])) {
            $data['tag_id'] = intval($_GET['id']);
            $findTag = M('tag')->where($data)->find();
            $this->assign($findTag);
            $this->display('addTag');
        }
    }

    public function deleteTag() {
        if (empty($_POST['ids'])) {
            echo 0;
            exit();
        }
        $map['tag_id'] = array('in', $_POST['ids']);
        $_LOG['uid'] = $this->mid;
        $_LOG['type'] = '2';
        $data[] = '内容-标签管理'; // '内容 - 广告管理 '
        $data[] = M('tag')->where($map)->select();
        $_LOG['data'] = serialize($data);
        $_LOG['ctime'] = time();
        M('AdminLog')->add($_LOG);
        echo M('tag')->where($map)->delete() ? '1' : '0';
    }

    public function apply() {
        import("ORG.Util.Page"); // 导入分页类
        if ($_GET['id'] != null && $_GET['id'] != "") {
            $map['id'] = array("in", explode(',', $_GET['id']));
            $this->assign("id", $_GET['id']);
            $this->assign("search", "yes");
        }
        if ($_GET['email'] != null && $_GET['email'] != "") {
            $map['email'] = array("in", explode(',', $_GET['email']));
            $this->assign("email", $_GET['email']);
            $this->assign("search", "yes");
        }
        if ($_GET['status'] != null && $_GET['status'] != "") {
            $map['status'] = $_GET['status'];
            $this->assign("status", $_GET['status']);
            $this->assign("search", "yes");
        }

        $count = M('apply')->where($map)->count();
        $page = new Page($count, 20);
        $data = M('apply')->where($map)->order('id desc')->limit($page->firstRow . ',' . $page->listRows)->select();
        $show = $page->show(); // 分页显示输出
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('data', $data);

        $this->display();
    }

    public function doapply() {
        if (empty($_POST['ids']) || empty($_POST['status'])) {
            echo 0;
            exit();
        }
        $map['id'] = array('in', $_POST['ids']);

        if ($_POST['status'] === "1") {
            $emailList = M('apply')->where($map)->field('email')->select();
            foreach ($emailList as $k => $v) {
                $invitecode = md5($this->mid . time() . "^@*&@*HF*@&#&@*(*@#" . $k . $v);

                $list[$k]['email'] = $v;
                $list[$k]['invitecode'] = $invitecode;

                $data[$k]['uid'] = $this->mid;
                $data[$k]['code'] = $invitecode;
                $data[$k]['is_used'] = 0;
            }

            $addInvite = M('invitecode')->addAll($data);
            if ($addInvite === false) {
                echo '0';
                exit();
            }

            foreach ($list as $k => $v) {
                $this->activate($v['email'], $v['invitecode']);
            }
        }

        $res = M('apply')->where($map)->setField('status', $_POST['status']);
        if ($res === false) {
            echo '0';
            exit();
        }

        echo 1;
    }

    /**
     * 发送申请通过邮件
     * @param string $email 邮箱地址
     * @param string $invite 邀请信息
     * @param int $is_resend 重发
     */
    private function activate($email, $invite = '') {
        //设置激活路径
        $register_url = URL('home/Public/showIndex', array('invite' => $invite, 'type' => "register", 'email' => $email['email']));
        $THEME_URL = THEME_URL;
        $date = date("Y年m月d日");
        //设置邮件模板
        $body = <<<EOD
<table width="445" cellspacing="0" cellpadding="0" border="0" style="margin:0 auto;background-color:#fff">
	<tr>
		<td>
			<img alt="择言" src="$THEME_URL/css/img/email/logo.png" width="445" height="60" style="display:block;">
		</td>
	</tr>
	<tr>
		<td style="padding:45px 10px 45px 100px;border:1px solid #E1E1E1;">
			<p style="margin:0;padding:0;color:#333;font-size:14px;line-height:60px;">亲爱的用户</p>
			<p style="margin:0;padding:0;color:#333;font-size:14px;line-height:30px;">您的邀请码如下：</p>
            <p style="margin:0;padding:0;color:#333;font-size:12px;line-height:30px;color:#096;"><b>$invite</b></p>
            <p style="margin:0;padding:0;color:#333;font-size:14px;line-height:50px;">邀请码已匹配，点击注册按钮完成注册。</p>
			<p style="margin:0;padding:0;width:243px;height:40px;border-bottom:2px solid #007A52;font-size:14px;line-height:18px;background-color:#096;text-align:center;"><a target="_blank" href="$register_url" style="display:block;text-decoration:none;outline:none;color:#fff;line-height:40px;">点击注册</a></p>
			<p style="margin:20px 0 0 0;padding:0;color:#333;font-size:12px;line-height:24px;">$date</p>
			<p style="margin:0;padding:0;color:#999;font-size:12px;line-height:24px;">此邮件为系统自动发出的邮件，请勿直接回复。</p>
		</td>
	</tr>
</table>
EOD;
        // 发送邮件
        try {
            $ret = common('Email')->SendMail($email, $body, "邀请码申请成功");
            if ($ret)
                return $ret;
            else
                return 1;
        } catch (Exception $e) {  //接收抛出了但没有处理的所有异常
            return "error";
            exit();
        }
    }

    public function feedback() {
        import("ORG.Util.Page"); // 导入分页类
        if ($_GET['id'] != null && $_GET['id'] != "") {
            $map['id'] = array("in", explode(',', $_GET['id']));
            $this->assign("id", $_GET['id']);
            $this->assign("search", "yes");
        }
        if ($_GET['uid'] != null && $_GET['uid'] != "") {
            $map['uid'] = array("in", explode(',', $_GET['uid']));
            $this->assign("uid", $_GET['uid']);
            $this->assign("search", "yes");
        }
        if ($_GET['data'] != null && $_GET['data'] != "") {
            $map['data'] = array("like", "%" . $_GET['data'] . "%");
            $this->assign("content", $_GET['data']);
            $this->assign("search", "yes");
        }
        $count = M('user_feedback')->where($map)->count();
        $page = new Page($count, 20);
        $data = M("user_feedback")->where($map)->order('`id` ASC')->limit($page->firstRow . ',' . $page->listRows)->select();
        $show = $page->show(); // 分页显示输出
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('data', $data);
        $this->display();
    }

    public function delFeedback() {
        if ($_POST['ids'] == null || $_POST['ids'] == "") {
            echo 0;
            exit();
        }

        $map['id'] = array("in", $_POST['ids']);
        $res = M("user_feedback")->where($map)->delete();
        echo $res ? 1 : 0;
    }

}

?>
